import { ipcMain, BrowserWindow } from "electron";
import * as windowManager from "./modules/windowManager";
import * as systemFeatures from "./modules/systemFeatures";
import {
  startFileTransferService,
  stopFileTransferService,
} from "./modules/networkTransfer";
import { createDataMonitor } from "./modules/dataMonitor";
import {
  StartNetworkTransferType,
  StopNetworkTransferType,
} from "electron/types";
import {
  getSoftwarePath,
  startExternalSoftware,
} from "./modules/startExternalSoftware";

export function registerIpcHandlers({
  getMainWindow,
  getSpeedBallWindow,
  toggleSpeedBall,
  updateDataMonitorWindows,
}: {
  getMainWindow: () => BrowserWindow | null;
  getSpeedBallWindow: () => BrowserWindow | null;
  toggleSpeedBall: (show: boolean) => void;
  updateDataMonitorWindows: () => void;
}) {
  // 网速球切换
  ipcMain.handle("toggleSpeedBall", (_, show: boolean) => {
    toggleSpeedBall(show);
    updateDataMonitorWindows();
  });

  // 系统通知
  ipcMain.handle("systemNotice", (_, data: { title: string; body: string }) => {
    systemFeatures.showSystemNotice(data);
  });

  // 设置窗口置顶
  ipcMain.handle("setAlwaysOnTop", (_, type: boolean) => {
    systemFeatures.setAlwaysOnTop(getMainWindow(), type);
  });

  // 执行系统命令
  ipcMain.handle("exec", (_, command: string) => {
    systemFeatures.executeCommand(command);
  });

  // 窗口抖动
  ipcMain.handle("shakeTimes", async () => {
    systemFeatures.shakeWindow(getMainWindow());
  });

  // 窗口操作
  ipcMain.handle("windowTitle", (_, type: string) => {
    systemFeatures.windowOperation(getMainWindow(), type);
  });

  // 网速球位置更新
  ipcMain.handle(
    "setNetworkBallPosition",
    (_, position: { x: number; y: number }) => {
      const speedBallWindow = getSpeedBallWindow();
      if (speedBallWindow) {
        speedBallWindow.setPosition(position.x, position.y);
      }
    },
  );

  // 内部网络文件传输
  ipcMain.handle(
    "internalNetworkFileTransfer",
    async (_, data: StartNetworkTransferType | StopNetworkTransferType) => {
      if (data.type === "start") {
        return await startFileTransferService(data.url);
      }
      return stopFileTransferService();
    },
  );

  // 选择文件夹
  ipcMain.handle("selectFile", async () => {
    return await systemFeatures.selectDirectory();
  });

  // 启动外部软件
  ipcMain.handle(
    "startExternalSoftware",
    async (_, name: keyof ReturnType<typeof getSoftwarePath>) => {
      startExternalSoftware(name);
    },
  );
}
